package LL2;

public class Main {
    //定义链表节点
    static class CircularListNode {
        private int val;  //链表的数据域
        private CircularListNode next; //链表的指针域

        public CircularListNode(int val) {
            this.val = val; //链表的数据域
            this.next = null; //链表的指针域
        }
    }

    // 添加操作：给循环链表追加节点
    private static void Append(CircularListNode head, int val) {
        if (head == null) {
            return;
        }
        CircularListNode cur = head;
        //1. 移动指针变量到末尾节点
        while (cur.next != head) {
            cur = cur.next;
        }
        //2. 新节点追加到末尾节点
        CircularListNode newNode = new CircularListNode(val);
        cur.next = newNode;
        newNode.next = head; //更改末尾节点的指向
    }

    // 打印循环链表
    private static void Print(CircularListNode head) {
        if (head == null) {
            return;
        }
        CircularListNode cur = head.next;
        if (cur == head) {  //只有一个节点的情况
            System.out.println(cur.val);
            return;
        }

        //1. 打印头节点
        System.out.print(head.val + "\t");
        //2. 遍历打印其他节点
        while (cur != head) {
            System.out.print(cur.val + "\t");
            cur = cur.next;
        }
        System.out.println();
    }

    // 删除操作：删除循环链表的末尾节点
    private static void Delete(CircularListNode head) {
        // cli为空 或者 只有1个节点
        if (head == null || head.next == head) {
            return;
        }
        CircularListNode cur = head;
        //1. 找到链表的倒数第2个节点
        while (cur.next.next != head) {
            cur = cur.next;
        }
        //2. 删除最后节点
        cur.next = head;
    }

    public static void main(String[] args) {
        //1. 一个节点组成的循环链表
        CircularListNode head = new CircularListNode(1);
        head.next = head;

        //2. 添加节点
        CircularListNode newNode = new CircularListNode(2);
        head.next = newNode;
        newNode.next = head;

        CircularListNode tmp = new CircularListNode(3);
        head.next.next = tmp;
        tmp.next = head;

        //3.删除节点
        head.next.next = head;

        System.out.println("#########################  方法封装  #########################");
        //4. 追加链表节点
        CircularListNode root = new CircularListNode(0);
        root.next = root; //构成循环链表
        for (int i = 1; i < 11; i++) {
            Append(root, i);
        }

        //5. 打印链表节点
        Print(root);

        //6. 删除链表节点
        Delete(root);
        Print(root);

        Delete(root);
        Print(root);
    }
}